package com.example.common.util.poi_tl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zjarlin
 * @since 2023/3/10 09:56
 */
public class PoiTlUtil {
    // 定义一个正则表达式，匹配图片文件的扩展名
    static String export(Map<String, Object> model, String absolutePath, String outPath) throws IOException {
        //循环表格行插件
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        ConfigureBuilder builder = Configure.builder();
        //对于集合类型处理
        Set<String> tabVarNames = model.entrySet().stream().filter(e -> {
            Class<?> aClass = e.getValue().getClass();
            boolean isCollectionType = Collection.class.isAssignableFrom(aClass);
            return isCollectionType;
        }).filter(e -> {
            List value = (List) e.getValue();
            return !CollUtil.isEmpty(value) && !String.class.isAssignableFrom(value.get(0).getClass());
        }).map(Map.Entry::getKey).collect(Collectors.toSet());
        for (String tabVarName : tabVarNames) {
            builder = builder.bind(tabVarName, policy);
        }
        Configure build = builder.build();
        //String absolutePath = new ClassPathResource(resourcePath).getAbsolutePath();
        model.forEach((key, value) -> {
            model.computeIfPresent(key, (k, v) -> {
                String strValue = String.valueOf(v);
                if (v instanceof String && Validator.isUrl(strValue)) {
                    // 如果v是图片url，则进行处理
                    return processImage(strValue);
                } else {
                    // 如果v不是图片url，则返回原有的v
                    return v;
                }
            });
        });
        XWPFTemplate render = XWPFTemplate.compile(absolutePath, build).render(model);
        BufferedOutputStream outputStream = FileUtil.getOutputStream(outPath);
        render.writeAndClose(outputStream);
        return outPath;
    }

    private static PictureRenderData processImage(String imageUrl) {
        // 对图片url进行处理的逻辑
        Pictures.PictureBuilder pictureBuilder = Pictures.ofUrl(imageUrl, PictureType.PNG);

        return pictureBuilder
            //.size(10, 10)
            .create();
    }
}
